﻿using System;

using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Threading;
using OpenNETCF.Threading;
using System.Globalization;
using InTheHand.Diagnostics;

namespace Microsoft.ApplicationBlocks.Mobile.Updater.Tools
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                return;
            }

            //Process processToWait = null;
            int pid = int.Parse(args[0]);
            string applicationId = args[1];

            MutexEx waitMutex = new MutexEx(true, String.Format(CultureInfo.InvariantCulture,
                "WaitApplication_{0}", applicationId));

            waitMutex.WaitOne();

            try
            {
                // Finds the process in the operating system information.
                // CRAP workaround - loops until the process with 'pid' disappears
                bool foundIt = true;
                do
                {
                    foundIt = false;
                    foreach (var process in ProcessHelper.GetProcesses())
                    {
                        if (process.Id == pid)
                        {
                            foundIt = true;
                            Thread.Sleep(500);
                            break;
                        }
                    }
                }
                while (foundIt);

                //processToWait = Process.GetProcessById(pid);

                //processToWait.WaitForExit();

            }
            catch (Exception ex)
            {
                Debug.WriteLine("GetProcessById exception: " + ex.Message);
                return;
            }

            // This will get the updater and perform all the pending updates automatically
            ApplicationUpdaterManager updater = null;
            try
            {
                // Initialize the Application Updater
                ApplicationUpdaterManager.Initialize(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase), null);

                updater = ApplicationUpdaterManager.GetUpdater(applicationId);
                updater.ActivationError += new ActivationErrorEventHandler(updater_ActivationError);
                updater.ResumePendingUpdates();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Activation exception: " + ex.Message);
            }


            waitMutex.ReleaseMutex();
        }

        static void updater_ActivationError(object sender, ManifestErrorEventArgs e)
        {
            MessageBox.Show("Activation exception: " + e.Exception.Message + "\r\n" + e.Exception.StackTrace);
        }
    }
}
